package com.etc.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class GetPositionUtil {
	//将字符拼接成字符串
	private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }
	
	public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            //关闭输入流
            is.close();
        }
    }
	public static String getAddrName() throws JSONException, IOException{
        //这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
        JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=2olq60T1b48C8XEDNHFTI0bamLMCANUG");
        /* 获取到的json对象：
         *         {"address":"CN|广东|广州|None|CHINANET|0|0","
         *         content":{"address_detail":{"province":"广东省","city":"广州市","street":"","district":"","street_number":"","city_code":257},
         *         "address":"广东省广州市","point":{"x":"113.30764968","y":"23.12004910"}},"status":0}
        */
        //这里我们可以输出json看一下具体格式
        System.out.println(json.toString());
 
        JSONObject content=json.getJSONObject("content");              //获取json对象里的content对象
        JSONObject addr_detail=content.getJSONObject("address_detail");//从content对象里获取address_detail
        StringBuilder sb = new StringBuilder(addr_detail.get("province").toString()+ addr_detail.get("city").toString());
        sb.append("中软ETC");
        return sb.toString();
    }
	public static void main(String[] args) throws JSONException, IOException {
		System.out.println(getAddrName());
	}
	
}
